﻿@model SmartAdmin.Data.Models.Product
@{
  ViewData["Title"] = "产品主档";
  ViewData["PageName"] = "products_index";
  ViewData["Heading"] = "<i class='fal fa-window text-primary'></i> 产品主档";
  ViewData["Category1"] = "主数据管理";
  ViewData["PageDescription"] = "";
}
<div class="row">
  <div class="col-lg-12 col-xl-12">
    <div id="panel-1" class="panel">
      <div class="panel-hdr">
        <h2>
          产品主档
        </h2>
        <div class="panel-toolbar">
          <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"><i class="fal fa-window-minimize"></i></button>
          <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"><i class="fal fa-expand"></i></button>
        </div>

      </div>
      <div class="panel-container enable-loader show">
        <div class="loader"><i class="fal fa-spinner-third fa-spin-4x fs-xxl"></i></div>
        <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0  text-muted bg-subtlelight-fade ">
          <div class="row no-gutters align-items-center">
            <div class="col">
              <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") -->
              <div class="btn-group btn-group-sm">
                <button onclick="appendItem()" class="btn btn-default">
                  <span class="fal fa-plus mr-1"></span> 新增
                </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="deletebutton" disabled onclick="removeItem()" class="btn btn-default">
                  <span class="fal fa-times mr-1"></span> 删除
                </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="savebutton" disabled onclick="acceptChanges()" class="btn btn-default">
                  <span class="fal fa-save mr-1"></span> 保存
                </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="cancelbutton" disabled onclick="rejectChanges()" class="btn btn-default">
                  <span class="fal fa-ban mr-1"></span> 取消
                </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button onclick="reload()" class="btn btn-default"> <span class="fal fa-search mr-1"></span> 查询 </button>
                <button type="button" class="btn btn-default dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  <span class="sr-only">Toggle Dropdown</span>
                </button>
                <div class="dropdown-menu dropdown-menu-animated">
                  <a class="dropdown-item js-waves-on" href="javascript:void()"> 我的记录 </a>
                  <div class="dropdown-divider"></div>
                  <a class="dropdown-item js-waves-on" href="javascript:void()"> 自定义查询 </a>
                </div>
              </div>
              <div class="btn-group btn-group-sm hidden-xs">
                <button type="button" onclick="importExcel.upload()" class="btn btn-default"><span class="fal fa-cloud-upload mr-1"></span> 导入 </button>
                <button type="button" class="btn btn-default  dropdown-toggle dropdown-toggle-split waves-effect waves-themed" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  <span class="sr-only">Toggle Dropdown</span>
                </button>
                <div class="dropdown-menu dropdown-menu-animated">
                  <a class="dropdown-item js-waves-on" href="javascript:importExcel.downloadtemplate()">
                    <span class="fal fa-download"></span> 下载模板
                  </a>
                </div>
              </div>
              <div class="btn-group btn-group-sm hidden-xs">
                <button onclick="exportExcel()" class="btn btn-default">
                  <span class="fal fa-file-export mr-1"></span>  导出
                </button>
              </div>

            </div>

          </div>

        </div>
        <div class="panel-content">
          <div class="table-responsive">
            <table id="companies_datagrid">
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- 弹出窗体form表单 -->
<div id="productdetailwindow" class="easyui-window"
     title="明细数据"
     data-options="modal:true,
                    closed:true,
                    minimizable:false,
                    collapsible:false,
                    maximized:false,
                    iconCls:'fal fa-window',
                    onBeforeClose:function(){
                      var that = $(this);
                      if(producthasmodified()){
                        $.messager.confirm('确认','你确定要放弃保存修改的记录?',function(r){
                        if (r){
                          var opts = that.panel('options');
                          var onBeforeClose = opts.onBeforeClose;
                          opts.onBeforeClose = function(){};
                          that.panel('close');
                          opts.onBeforeClose = onBeforeClose;
                          hook = false;
                        }
                        });
                        return false;
                      }
                    },
                    onOpen:function(){
                       $(this).window('vcenter');
                       $(this).window('hcenter');
                    },
                    onRestore:function(){
                    },
                    onMaximize:function(){
                    }
                    " style="width:820px;height:420px;display:none">
  <!-- toolbar -->
  <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0  text-muted bg-subtlelight-fade sticky-top">
    <div class="d-flex flex-row-reverse pr-4">
      <div class="btn-group btn-group-sm mr-1">
        <button name="saveitembutton" onclick="saveproductitem()" class="btn btn-default">
          <i class="fal fa-save"></i> 保存
        </button>
      </div>
      <div class="btn-group btn-group-sm mr-1" id="deleteitem-btn-group">
        <button onclick="deleteproductitem()" class="btn btn-danger">
          <i class="fal fa-trash-alt"></i> 删除
        </button>
      </div>
    </div>
  </div>
  <div class="panel-container show">
    <div class="container">
      <div class="panel-content">
        <form id="product_form"
              class="easyui-form form-horizontal p-1"
              method="post"
              data-options="novalidate:true,
                            onChange: function(target){
                              hook = true;
                              $('button[name*=\'saveitembutton\']').prop('disabled', false);
                             },
                             onLoadSuccess:function(data){
                               hook = false;
                               $('button[name*=\'saveitembutton\']').prop('disabled', true);
                             }">
          @Html.AntiForgeryToken()
          <!--Primary Key-->
          @Html.HiddenFor(model => model.Id)
          <fieldset class="form-group">
            <!-- begin row -->
            <!--名称-->
            <div class="row h-100 justify-content-center align-items-center">
              <label class="col-md-2 pr-1 form-label text-right"><span class="text-danger">*</span> @Html.DisplayNameFor(model => model.Name)</label>
              <div class="col-md-4 mb-1 pl-1">
                <input id="@Html.IdFor(model => model.Name)"
                       name="@Html.NameFor(model => model.Name)"
                       value="@Html.ValueFor(model => model.Name)"
                       tabindex="0" required
                       class="easyui-textbox"
                       style="width:100%"
                       type="text"
                       data-options="prompt:'@Html.DescriptionFor(model => model.Name)',
								 required:true,
                                 validType: 'length[0,128]'
                                 " />
              </div>
              <label class="col-md-2 pr-1 form-label text-right ">@Html.DisplayNameFor(model => model.Model)</label>
              <div class="col-md-4 mb-1 pl-1">
                <input id="@Html.IdFor(model => model.Model)"
                       name="@Html.NameFor(model => model.Model)"
                       value="@Html.ValueFor(model => model.Model)"
                       tabindex="1" required
                       class="easyui-textbox"
                       style="width:100%"
                       type="text"
                       data-options="prompt:'@Html.DescriptionFor(model => model.Model)',
								 required:true,validType: 'length[0,60]'
                                 " />
              </div>
              <label class="col-md-2 pr-1 form-label text-right">@Html.DisplayNameFor(model => model.Unit)</label>
              <div class="col-md-4 mb-1 pl-1">
                <input id="@Html.IdFor(model => model.Unit)"
                       name="@Html.NameFor(model => model.Unit)"
                       value="@Html.ValueFor(model => model.Unit)"
                       tabindex="2"
                       class="easyui-textbox"
                       style="width:100%"
                       type="text"
                       data-options="prompt:'@Html.DescriptionFor(model => model.Unit)',
								 required:false,
                                 validType: 'length[0,10]'
                                 " />
              </div>
              <label class="col-md-2 pr-1 form-label text-right">@Html.DisplayNameFor(model => model.UnitPrice)</label>
              <div class="col-md-4 mb-1 pl-1">
                <input id="@Html.IdFor(model => model.UnitPrice)"
                       name="@Html.NameFor(model => model.UnitPrice)"
                       value="@Html.ValueFor(model => model.UnitPrice)"
                       tabindex="3"
                       class="easyui-numberbox"
                       style="width:100%"
                       type="text"
                       data-options="prompt:'@Html.DescriptionFor(model => model.UnitPrice)',
								 required:true, formatter:numberformatter,parser:parsernumber
                                 " />
              </div>

            </div>
          </fieldset>
        </form>
      </div>
    </div>
  </div>
</div>


@await Component.InvokeAsync("ImportExcel", new ImportExcelOptions
{
  entity = "Product",
  folder = "Products",
  url = "/Products",
  tpl = "Product.xlsx"


})

@section HeadBlock {
  
  <link href="~/css/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.css" rel="stylesheet" asp-append-version="true" />
  <link href="~/js/easyui/themes/insdep/easyui.css" rel="stylesheet" asp-append-version="true" />
}
@section ScriptsBlock {
  <script src="~/js/dependency/numeral/numeral.min.js" asp-append-version="true"></script>
  <script src="~/js/dependency/moment/moment.js" asp-append-version="true"></script>
  <script src="~/js/formplugins/bootstrap-daterangepicker/bootstrap-daterangepicker.js" asp-append-version="true"></script>
  <script src="~/js/easyui/jquery.easyui.min.js" asp-append-version="true"></script>
  <script src="~/js/easyui/plugins/datagrid-filter.js" asp-append-version="true"></script>
  <script src="~/js/easyui/plugins/columns-ext.js" asp-append-version="true"></script>
  <script src="~/js/easyui/plugins/columns-reset.js" asp-append-version="true"></script>
  <script src="~/js/easyui/locale/easyui-lang-zh_CN.js" asp-append-version="true"></script>
  <script src="~/js/easyui/jquery.easyui.component.js" asp-append-version="true"></script>
  <script src="~/js/plugin/filesaver/FileSaver.js" asp-append-version="true"></script>
  <script src="~/js/plugin/jquery.serializejson/jquery.serializejson.js" asp-append-version="true"></script>
  <script src="~/js/jquery.custom.extend.js" asp-append-version="true"></script>
  <script src="~/js/jquery.extend.formatter.js" asp-append-version="true"></script>
  <script>
    //全屏事件
    document.addEventListener('panel.onfullscreen', () => {
      $dg.treegrid('resize');
    });
        var $dg = $('#companies_datagrid');
        var EDITINLINE = true;
        var product = null;
    var editIndex = undefined;
    //下载Excel导入模板

    //执行导出下载Excel
    function exportExcel() {
      const filterRules = JSON.stringify($dg.datagrid('options').filterRules);
      console.log(filterRules);
      $.messager.progress({ title: '请等待', msg: '正在执行导出...' });
      let formData = new FormData();
      formData.append('filterRules', filterRules);
      formData.append('sort', 'Id');
      formData.append('order', 'asc');
      $.postDownload('/Products/ExportExcel', formData).then(res => {
        $.messager.progress('close');
        toastr.success('导出成功!');
      }).catch(err => {
        //console.log(err);
        $.messager.progress('close');
        $.messager.alert('导出失败', err.statusText, 'error');
      });

    }
            //弹出明细信息
    function showDetailsWindow(id, index) {
      const product = $dg.datagrid('getRows')[index];
      openProductDetailWindow(product, 'Modified');
    }
    function reload() {
      $dg.datagrid('uncheckAll');
      $dg.datagrid('reload');
    }
            //新增记录
    function appendItem() {
      product = {
        Address: '-',
        RegisterDate: moment().format('YYYY-MM-DD HH:mm:ss'),
      };
      if (!EDITINLINE) {
        //弹出新增窗口
        openProductDetailWindow(product, 'Added');
      } else {
        if (endEditing()) {
          //对必填字段进行默认值初始化
          $dg.datagrid('insertRow',
            {
              index: 0,
              row: product
            });
          editIndex = 0;
          $dg.datagrid('selectRow', editIndex)
            .datagrid('beginEdit', editIndex);
          hook = true;
        }
      }
    }
            //删除编辑的行
    function removeItem() {
      if (this.$dg.datagrid('getChecked').length <= 0 && EDITINLINE) {
        if (editIndex !== undefined) {
          const delindex = editIndex;
          $dg.datagrid('cancelEdit', delindex)
            .datagrid('deleteRow', delindex);
          hook = true;
          $("button[name*='savebutton']").prop('disabled', false);
          $("button[name*='cancelbutton']").prop('disabled', false);
        } else {
          const rows = $dg.datagrid('getChecked');
          rows.slice().reverse().forEach(row => {
            const rowindex = $dg.datagrid('getRowIndex', row);
            $dg.datagrid('deleteRow', rowindex);
            hook = true;
          });
        }
      } else {
        deletechecked();
      }
    }
    //删除选中的行
    function deleteChecked() {
      const checked = $dg.datagrid('getChecked').filter(item => item.Id != null && item.Id > 0).map(item => {
        return item.Id;
      });;
      if (checked.length > 0) {
        deleteRows(checked);
      } else {
        $.messager.alert('提示', '请先选择要删除的记录!', 'question');
      }
    }
    //执行删除
    function deleteRows(selected) {
      $.messager.confirm('确认', `你确定要删除这 <span class='badge badge-icon position-relative'>${selected.length} </span> 行记录?`, result => {
        if (result) {
          $.post('/Products/DeleteChecked', { id: selected })
            .done(response => {
              if (response.success) {
                toastr.error(`成功删除 [${selected.length}] 行记录`);
                reload();
              } else {
                $.messager.alert('错误', response.err, 'error');
              }
            })
            .fail((jqXHR, textStatus, errorThrown) => {
              $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
            });
        }
      });
    }
            //开启编辑状态
    function onClickCell(index, field) {

      product = $dg.datagrid('getRows')[index];
      const _actions = ['action', 'ck'];
      if (!EDITINLINE || $.inArray(field, _actions) >= 0) {
        return;
      }

      if (editIndex !== index) {
        if (endEditing()) {
          $dg.datagrid('selectRow', index)
            .datagrid('beginEdit', index);
          hook = true;
          editIndex = index;
          const ed = $dg.datagrid('getEditor', { index: index, field: field });
          if (ed) {
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
          }
        } else {
          $dg.datagrid('selectRow', editIndex);
        }
      }
    }
            //关闭编辑状态
    function endEditing() {

      if (editIndex === undefined) {
        return true;
      }
      if (this.$dg.datagrid('validateRow', editIndex)) {
        $dg.datagrid('endEdit', editIndex);
        return true;
      } else {
        const invalidinput = $('input.validatebox-invalid', $dg.datagrid('getPanel'));
        const fieldnames = invalidinput.map((index, item) => {
          return $(item).attr('placeholder') || $(item).attr('id');
        });
        $.messager.alert('提示', `${Array.from(fieldnames)} 输入有误.`, 'error');
        return false;
      }
    }
            //提交保存后台数据库
    function acceptChanges() {
      if (endEditing()) {
        if ($dg.datagrid('getChanges').length > 0) {
          const inserted = $dg.datagrid('getChanges', 'inserted').map(item => {
            item.TrackingState = 1;
            return item;
          });
          const updated = $dg.datagrid('getChanges', 'updated').map(item => {
            item.TrackingState = 2
            return item;
          });
          const deleted = $dg.datagrid('getChanges', 'deleted').map(item => {
            item.TrackingState = 3
            return item;
          });
          //过滤已删除的重复项
          const changed = inserted.concat(updated.filter(item => {
            return !deleted.includes(item);
          })).concat(deleted);
          //$.messager.progress({ title: '请等待', msg: '正在保存数据...', interval: 200 });
          $.post('/Products/AcceptChanges', { products: changed })
            .done(response => {
              //$.messager.progress('close');
              //console.log(response);
              if (response.success) {
                toastr.success('保存成功');
                $dg.datagrid('acceptChanges');
                reload();
                hook = false;
              } else {
                $.messager.alert('错误', response.err, 'error');
              }
            })
            .fail((jqXHR, textStatus, errorThrown) => {
              //$.messager.progress('close');
              $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
            });
        }
      }
    }
    function rejectChanges() {
      $dg.datagrid('rejectChanges');
      editIndex = undefined;
      hook = false;
    }
    $(document).ready(function () {
      //定义datagrid结构
      $dg.datagrid({
        rownumbers: true,
        checkOnSelect: false,
        selectOnCheck: false,
        idField: 'Id',
        sortName: 'Id',
        sortOrder: 'desc',
        remoteFilter: true,
        singleSelect: true,
        method: 'get',
        onClickCell: onClickCell,
        clientPaging: false,
        pagination: true,
        striped: true,
        filterRules: [],
        onHeaderContextMenu: function (e, field) {
          e.preventDefault();
          $(this).datagrid('columnMenu').menu('show', {
            left: e.pageX,
            top: e.pageY
          });
        },
        onBeforeLoad: function () {
          $('.enable-loader').removeClass('enable-loader')
        },
        onLoadSuccess: function (data) {
          editIndex = undefined;
          $("button[name*='deletebutton']").prop('disabled', true);
          $("button[name*='savebutton']").prop('disabled', true);
          $("button[name*='cancelbutton']").prop('disabled', true);
        },
        onCheckAll: function (rows) {
          if (rows.length > 0) {
            $("button[name*='deletebutton']").prop('disabled', false);
          }
        },
        onUncheckAll: function () {
          $("button[name*='deletebutton']").prop('disabled', true);
        },
        onCheck: function () {
          $("button[name*='deletebutton']").prop('disabled', false);
        },
        onUncheck: function () {
          const checked = $(this).datagrid('getChecked').length > 0;
          $("button[name*='deletebutton']").prop('disabled', !checked);
        },
        onSelect: function (index, row) {
          product = row;
        },
        onBeginEdit: function (index, row) {
          //const editors = $(this).datagrid('getEditors', index);

        },
        onEndEdit: function (index, row) {
          editIndex = undefined;
        },
        onBeforeEdit: function (index, row) {
          editIndex = index;
          row.editing = true;
          $("button[name*='deletebutton']").prop('disabled', false);
          $("button[name*='cancelbutton']").prop('disabled', false);
          $("button[name*='savebutton']").prop('disabled', false);
          $(this).datagrid('refreshRow', index);
        },
        onAfterEdit: function (index, row) {
          row.editing = false;
          editIndex = undefined;
          $(this).datagrid('refreshRow', index);
        },
        onCancelEdit: function (index, row) {
          row.editing = false;
          editIndex = undefined;
          $("button[name*='deletebutton']").prop('disabled', true);
          $("button[name*='savebutton']").prop('disabled', true);
          $("button[name*='cancelbutton']").prop('disabled', true);
          $(this).datagrid('refreshRow', index);
        },
        frozenColumns: [[
          /*开启CheckBox选择功能*/
          { field: 'ck', checkbox: true },
          {
            field: 'action',
            title: '操作',
            width: 85,
            sortable: false,
            resizable: true,
            formatter: function showdetailsformatter(value, row, index) {
              if (!row.editing) {
                return `<div class="btn-group">\
                                                         <button onclick="showDetailsWindow('${row.Id}',  ${index})" class="btn btn-primary btn-sm btn-icon waves-effect waves-themed" title="查看明细" ><i class="fal fa-edit"></i> </button>\
                                                         <button onclick="deleteRows(['${row.Id}'],${index})" class="btn btn-primary btn-sm btn-icon waves-effect waves-themed" title="删除记录" ><i class="fal fa-times"></i> </button>\
                                                    </div>`;
              } else {
                return `<button class="btn btn-primary btn-sm btn-icon waves-effect waves-themed" disabled title="查看明细"  ><i class="fal fa-edit"></i> </button>`;
              }
            }
          }
        ]],
        columns: [[
          {    /*名称*/
            field: 'Name',
            title: '<span class="text-danger">*<span> @Html.DisplayNameFor(model => model.Name)',
            width: 200,
            hidden: false,
            editor: {
              type: 'textbox',
              options: { prompt: '@Html.DescriptionFor(model => model.Name)', required: true, validType: 'length[0,128]' }
            },
            sortable: true,
            resizable: true
          },
          {    /*规格型号*/
            field: 'Model',
            title: '@Html.DisplayNameFor(model => model.Model)',
            width: 120,
            hidden: false,
            editor: {
              type: 'textbox',
              options: { prompt: '@Html.DescriptionFor(model => model.Model)', required: true, validType: 'length[0,60]' }
            },
            sortable: true,
            resizable: true
          },
          {    /*单位*/
            field: 'Unit',
            title: '@Html.DisplayNameFor(model => model.Unit)',
            width: 200,
            hidden: false,
            editor: {
              type: 'textbox',
              options: { prompt: '@Html.DescriptionFor(model => model.Unit)', required: false, validType: 'length[0,10]' }
            },
            sortable: true,
            resizable: true
          },
          {    /*单价*/
            field: 'UnitPrice',
            title: '@Html.DisplayNameFor(model => model.UnitPrice)',
            width: 120,
            hidden: false,
            editor: {
              type: 'numberbox',
              options: { prompt: '@Html.DescriptionFor(model => model.UnitPrice)', required: true}
            },
            sortable: true,
            resizable: true,
            formatter: numberformatter
          }
        ]]
      }).datagrid('columnMoving')
        .datagrid('resetColumns')
        .datagrid('enableFilter', [
        ])
        .datagrid('load', '/Products/GetData');
    }
    );

  </script>
  <script type="text/javascript">
    //判断新增编辑状态
    var MODELSTATE = 'Added';
    var productid = null;
    function openProductDetailWindow(data, state) {
      MODELSTATE = state;
      initproductdetailview();
      productid = (data.Id || 0);
      $("#productdetailwindow").window("open");
      $('#product_form').form('reset');
      $('#product_form').form('load', data);
    }
    //删除当前记录
    function deleteproductitem() {
      $.messager.confirm('确认', '你确定要删除该记录?', result => {
        if (result) {
          const url = `/Products/Delete/${productid}`;
          $.get(url).done(res => {
            if (res.success) {
              toastr.success("删除成功");
              $("#productdetailwindow").window("close");
              reload();
            } else {
              $.messager.alert("错误", res.err, "error");
            }
          });
        }
      });
    }
    //async 保存数据
    async function saveproductitem() {
      const $productform = $('#product_form');
      if ($productform.form('enableValidation').form('validate')) {
        let product = $productform.serializeJSON();
        let url = '/Products/Edit';
        //判断是新增或是修改方法
        if (MODELSTATE === 'Added') {
          url = '/Products/Create';
        }
        var token = $('input[name="__RequestVerificationToken"]', $productform).val();
        //$.messager.progress({ title: '请等待', msg: '正在保存数据...', interval: 200 });
        $.ajax({
          type: "POST",
          url: url,
          data: {
            __RequestVerificationToken: token,
            product: product
          },
          dataType: 'json',
          contentType: 'application/x-www-form-urlencoded; charset=utf-8'
        })
          .done(response => {
            //$.messager.progress('close');
            if (response.success) {
              hook = false;
              $productform.form('disableValidation');
              $dg.datagrid('reload');
              $('#productdetailwindow').window("close");
              toastr.success("保存成功");
            } else {
              $.messager.alert("错误", response.err, "error");
            }
          })
          .fail((jqXHR, textStatus, errorThrown) => {
            //$.messager.progress('close');
            $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
          });
      }
    }
    //关闭窗口
    function closeproductdetailwindow() {
      $('#productdetailwindow').window('close');
    }

    //判断是否有没有保存的记录
    function producthasmodified() {
      return hook;
    }


    function initproductdetailview() {
      //判断是否显示功能按钮

    }
  </script>
}
